var prefix = ctx +"module/terminal"
$(function() {
    load();
});
function load(){
    layui.use(['form','laydate','table'], function() {
        var form = layui.form ,laydate = layui.laydate
            table = layui.table;//载入table模块
        laydate.render({
            elem: '#begin_date',
            isInitValue: false,
        });
        laydate.render({
            elem: '#end_date',
            isInitValue: false,
        });
        var searchParams = {};
        searchParams['search_eq_shopId']=$('#shopId').val();
        searchParams['health']=$('#health').val();

        //初始化table
        table.render({
            elem: '#exampleTable',//承载数据的table Id
            url: prefix + "/health/list",//请求数据连接
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter'],
            cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
            even: true,//是否开启隔行变色
            loading:true,//是否显示加载条
            where :{
                searchParams:searchParams,
                sorts:{"id":"desc"}
            },
            //page: true,//是否分页
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: [ 'prev', 'page', 'next', 'skip', 'count','limit'] //自定义分页布局
            },
            cols: [[
                { type : 'checkbox',fixed : 'left' },
                { field : 'shopName',  title : '所属企业', align : 'center', width:200 },
                { field : 'terminalNum',  title : '设备编号', align : 'center',
                    templet: function (item) {
                        return "<a href=\"javascript:void(0);\" onclick='goTerminalInfo("+item.terminalId+")' style='color:blue;'>" +
                            item.terminalNum+
                            "   </a>";
                    },
                },
                { field : 'terminalName',  title : '设备名称', align : 'center',
                    templet: function (item) {
                        return "<a href=\"javascript:void(0);\" onclick='goTerminalInfo("+item.terminalId+")' style='color:blue;'>" +
                            item.terminalName+
                            "   </a>";
                    },
                },
                { title : '二维码', align : 'center',
                    templet: function (item) {
                        return "<a href=\"javascript:void(0);\" imgurl=\""+item.qrcodeImg+"\" class=\"grid-column-qrcode text-muted\">" +
                            "           <i class=\"fa fa-qrcode\"></i>" +
                            "       </a>"+
                            "       &nbsp;&nbsp;<a href='"+prefix + "/download/"+item.terminalNum+"' download='terminal_qr_"+item.terminalNum+".jpg'><i class=\"fa fa-download\"></i>No."+item.terminalNum+"</a>";
                    },
                },
                { field : 'deviceFittingName',  title : '保养点', align : 'center',   },
                { field : 'healthRunhuaji',  title : '使用润滑剂', align : 'center',   },
                { title : '保养周期', align : 'center',
                    templet: function (item) {
                        return '1次/' + item.healthCount + (loadCategory('clean-cycle-type')[item.healthCountUnit] ? loadCategory('clean-cycle-type')[item.healthCountUnit] : '');
                    },
                },
                { title : '保养状态', align : 'center',
                    templet: function (item) {
                        if(item.currentHealthCount > 0){
                            return '<span class="label label-success">当前周期已保养</span>';
                        }else{
                            return '<span class="label label-danger">当前周期未保养</span>';
                        }
                    },
                },
                { field : 'lastHealthTime',  title :'最后保养时间', align : 'center',   },
                { title: '操作', minWidth:180, templet: '#currentTableBar',fixed: "right", align: "center"}
            ]],
            id: 'currentTableId',//表格Id
            done: function(res, curr, count){
                $(".grid-column-qrcode").each(function() {
                    $(this).click(function() {
                        previewImg(this);
                    })
                });
            } //解决最右侧列不能固定的问题
        });
        /**
         * 操作栏tool  监听事件
         */
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') {  // 监听添加操作
                console.log('obj',obj.data.id)
                edit(obj.data.id);
            } else if (obj.event === 'delete') {  // 监听删除操作
                console.log('obj',obj.data.id)
                remove(obj.data.id);
            }else if (obj.event === 'record') {  // 监听删除操作
                goRecordList(obj.data.id);
            }else if (obj.event === 'qrcode') {  // 监听删除操作
                resetQrcode(obj.data.terminalId);
            }
        });
        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            reLoad();
            return false;
        });

        /**
         * 操作栏tool  监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'back') {  // 监听添加操作
                goBack();
            }else if (obj.event === 'upload') {  // 批量上传终端
                batchAdd();
            } else if(obj.event === 'export'){
                exportExcel()
            }else if(obj.event === 'batchRemove'){
                var checkStatus = table.checkStatus('currentTableId'),data = checkStatus.data;
                checkedArr = data;
                var ids = [];
                for(var index in checkedArr){
                    ids.push(checkedArr[index].id);
                }
                if (ids.length < 1) {
                    layer.msg('无选中项');
                    return false;
                }
                batchRemove(ids);
            }else if(obj.event === 'batchQrcode'){
                var checkStatus = table.checkStatus('currentTableId'),data = checkStatus.data;
                checkedArr = data;
                var ids = [];
                for(var index in checkedArr){
                    ids.push(checkedArr[index].terminalId);
                }
                if (ids.length < 1) {
                    layer.msg('无选中项');
                    return false;
                }
                batchQrcode(ids);
            }
        });
    });
}
function exportExcel(){
    var begin_date = $("#begin_date").val();
    var end_date = $("#end_date").val();
    var isClean = $("#isClean").val();
    var shopId = $("#shopId").val();
    var checkState = $("#checkState").val();
    window.location.href = ctx + 'module/terminal/record/exportExcel?begin_date='
        +begin_date+'&end_date='+end_date+"&is_clean="+isClean+'&shopId='+shopId+'&checkState='+checkState;
}


function goBack(){
    var id = $("#shopId").val();
    window.location.href = ctx + 'module/terminal/'+id;
}

function goTerminalInfo(id) {
    var index = layer.open({
        type : 2,
        title : '设备详情',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '550px' ],
        content : prefix + '/record/info/' + id // iframe的url
    });
    layer.full(index);
}

function resetQrcode(id){
    $.ajax({
        url : prefix + "/resetQrcode",
        type : "post",
        data : {
            'id' : id
        },
        success : function(r) {
            if (r.code==0) {
                layer.msg(r.msg);
                reLoad();
            }else{
                layer.msg(r.msg);
            }
        }
    });
}

function batchQrcode(ids) {
    $.ajax({
        type : 'POST',
        data : {
            "ids" : ids
        },
        url : prefix + '/batchQrcode',
        success : function(r) {
            if (r.code == 0) {
                layer.msg(r.msg);
                reLoad();
            } else {
                layer.msg(r.msg);
            }
        }
    });
}

function previewImg(obj) {
    console.log('obj',obj)
    var img = new Image();
    img.src = $(obj).attr("imgurl");
    console.log('img',$(obj).attr("imgurl"));
    var imgHtml = "<img src='" + img.src + "' width='400' height='400' style='margin: 25px 25px'/>";
    //弹出层
    layer.open({
        type: 1,
        // shade: true,
        shadeClose : true, // 点击遮罩关闭层
        title: false, //不显示标题
        area:[ '450px', '450px' ],
        content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        cancel: function () {

        }
    });
}

function reLoad() {
    var searchParams = {};
    searchParams['search_eq_shopId']=$('#shopId').val();
    searchParams['health']=$('#health').val();
    layui.use(['table'], function() {
        var table = layui.table;//载入table模块
        table.reload('currentTableId', {
            page: {curr: 1}
            , where: {
                searchParams: searchParams,
                sorts:{"id":"desc"}
            }
        }, 'data');
    });
}

function add() {
    var index = layer.open({
        type : 2,
        title : '增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '420px' ],
        content : prefix + '/add' // iframe的url
    });
    layer.full(index);
}

function batchAdd() {
    var index = layer.open({
        type : 2,
        title : '批量增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '320px' ],
        content : prefix + '/goBatchAddFitting' // iframe的url
    });
}

function goRecordList(id) {
    window.location.href = ctx + 'module/terminal/record/'+id;
}

function edit(id) {
    var index = layer.open({
        type : 2,
        title : '编辑',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '520px' ],
        content : prefix + '/edit/' + id // iframe的url
    });

    layer.full(index);
}
function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : prefix+"/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    reLoad();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}

function batchRemove(ids) {
    layer.confirm("确认要删除选中的'" + ids.length + "'条数据吗?", {
        btn : [ '确定', '取消' ]
        // 按钮
    }, function() {
        $.ajax({
            type : 'POST',
            data : {
                "ids" : ids
            },
            url : prefix + '/batchRemove',
            success : function(r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function() {});
}
